package queuedemo;

import java.util.LinkedList;
import java.util.Queue;

class MyStack {

    //利用队列实现栈
    //不能使用双端队列

    public Queue<Integer> queue1;
    public Queue<Integer> queue2;

    public MyStack() {
        //在构造方法里面实例化
        this.queue1 = new LinkedList<>();
        this.queue2 = new LinkedList<>();
    }

    /**
     * 压栈操作
     * @param x
     */
    public void push(int x) {
        if (empty()){
            queue1.offer(x);
            return;
        }
        if (!queue1.isEmpty()){
            queue1.offer(x);
        }else {
            queue2.offer(x);
        }
    }

    /**
     * 弹出栈顶元素
     * @return
     */
    public int pop() {
        if (empty()){
            //说明模拟的栈是空的
            return -1;
        }
        //找到不为空的元素，出size - 1 个元素
        if (!queue1.isEmpty()){
            int size = queue1.size();
            for (int i = 0; i < size - 1; i++) {
                queue2.offer(queue1.poll());
            }
            return queue1.poll();
        }else {
            int size = queue2.size();
            for (int i = 0; i < size - 1; i++) {
                queue1.offer(queue2.poll());
            }
            return queue2.poll();
        }
    }

    public int top() {
        if (empty()){
            //说明模拟的栈是空的
            return -1;
        }
        //找到不为空的元素，出size - 1 个元素
        if (!queue1.isEmpty()){
            int size = queue1.size();
            int tmp = -1;
            for (int i = 0; i < size; i++) {
                tmp = queue1.poll();
                queue2.offer(tmp);
            }
            return tmp;
        }else {
            int size = queue2.size();
            int tmp = -1;
            for (int i = 0; i < size - 1; i++) {
                tmp = queue2.poll();
                queue1.offer(tmp);
            }
            return tmp;
        }
    }

    public boolean empty() {
        return queue1.isEmpty() && queue2.isEmpty();
    }
}